package com.net.tool;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.dailyyoga.bitmapManager.YogaImageLoader.ImageLoaderListener;

public abstract class DownLoadTask implements PostTask {

	public String mUrl;
	DownloadToole mDownloadToole;

	ImageLoaderListener mImageLoaderListener;

	protected boolean mState = true;

	public DownLoadTask(String url) {
		mUrl = url;
	}

	public void setImageLoaderListener(ImageLoaderListener imageLoaderListener) {
		mImageLoaderListener = imageLoaderListener;
	}

	public boolean download() {
		try {
			download(mUrl);
			return true;
		} catch (Exception e) {

		}
		return false;
	}

	HttpURLConnection _httpConnection;

	public static String path = "/sdcard/.dailyyogaCN2/usericon/";

	public void download(String URl) throws IOException {

		try {
			downloadBitMap(URl + "_s");
		} catch (Exception e) {

			downloadBitMap(URl);
			saveSmallBitmap(getFileName(URl));
		}

	}

	private void saveSmallBitmap(String fileName) throws IOException {
		String small = fileName + "_s";
		File smallFile = new File(path + small);
		smallFile.createNewFile();

		Bitmap src = BitmapFactory.decodeFile(path + fileName);
		int w = src.getWidth();
		int h = src.getHeight();
		float k = w > h ? (90.0f / w) : (90.0f / h);
		Bitmap smallBitmap = Bitmap.createScaledBitmap(src, (int) (w * k),
				(int) (h * k), true);

		OutputStream outputStream = new FileOutputStream(smallFile);

		smallBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream);
		outputStream.flush();
		outputStream.close();

	}

	public void downloadBitMap(String name) throws IOException {

		File file = new File(path);

		file.mkdirs();

		file = new File(file, "tmp");

		if (!file.exists()) {
			file.createNewFile();
		}

		file = new File(path + getFileName(name.trim()));
		Log.d("downloadBitMap", "fileName" + file.getAbsolutePath() + "URl="
				+ name);
		if (!file.exists()) {
			_httpConnection = (HttpURLConnection) new URL(name.trim())
					.openConnection();
			InputStream inputStream = _httpConnection.getInputStream();

			FileOutputStream outputStream = new FileOutputStream(new File(path
					+ "tmp"));

			long serverLength = _httpConnection.getContentLength();

			int count = 0;

			int offset = 0;

			int progress = 0;

			byte[] _buffer = new byte[1024];
			while ((offset = inputStream.read(_buffer)) != -1) {
				Log.d("downloadImage", " down ing  =====");

				outputStream.write(_buffer, 0, offset);
				count++;
				progress += offset;

				if (mImageLoaderListener != null) {
					mImageLoaderListener.updateProgress(progress,
							(int) serverLength);
				}

			}
			outputStream.flush();
			outputStream.close();
			inputStream.close();

			if (count == 0) {

				throw new IOException("count == 0");
			}

			Log.d("downloadBitMap",
					"fileName=================" + file.getAbsolutePath());
			new File(path + "tmp").renameTo(file);

			Log.d("downloadBitMap", "下载完成" + file.getAbsolutePath());
		}

		// if (name.contains("+circle+")) {
		// Bitmap circle = DailyYogaTools.toRoundCorner(BitmapFactory
		// .decodeFile(path + getFileName(url)));
		// cancheToDisk(name, circle);
		// }

	}

	public static void cancheToDisk(String key, Bitmap bitmap) {
		// 2.缓存bitmap至/data/data/packageName/cache/文件夹中
		try {
			String fileName = getFileName(key);
			String filePath = path + "/" + fileName;
			// System.out.println("缓存到本地===" + filePath);
			FileOutputStream fos = new FileOutputStream(filePath);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);

		} catch (Exception e) {

		}
	}

	protected static String getFileName(String url) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(url.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			System.out.println("NoSuchAlgorithmException caught!");
			return null;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}

		byte[] byteArray = messageDigest.digest();
		StringBuffer md5StrBuff = new StringBuffer();
		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}
		return md5StrBuff.toString();
	}

	public Bitmap getBitmap(String fileName) throws IOException {
		FileInputStream fileInputStream = new FileInputStream(path + fileName
				+ "_s");
		Bitmap bitmap = BitmapFactory.decodeStream(fileInputStream);
		fileInputStream.close();
		return bitmap;
	}

	public void asyncCommend() {
		if (_httpConnection != null) {
			_httpConnection.disconnect();
		}
	}

	public void gbkDo() {
		mState = download();
	}

}
